<?
include_once "./arrayDataSetNN.php";

class NearestNeighbourClassifier
{
	private $dataSetPathSubj;
	private $dataSetPathObj;
	private	$dataSetSubj;
	private $dataSetObj;
	private $k;
	
	public function __construct($k)
	{
		$this -> dataSetSubj = array();
		$this -> dataSetObj = array();
		$this -> initializeDataSet();
		$this -> k = $k;
	}
	
	
	public function classify($sentence)
	{
		$distance = array();
		for ($i=0 ; $i < count($this->dataSetSubj) ; $i++)
		{
				$intersectSubj = array_intersect($sentence ,$this->dataSetSubj[$i]);
				$distSubj = count($sentence) - count($intersectSubj); 
				array_push($distance, array("dist" => $distSubj, "class" => 'subj'));					

				$intersectObj = array_intersect($sentence,$this -> dataSetObj[$i]);
				$distObj = count($sentence) - count($intersectObj); 
				array_push($distance, array("dist" => $distObj, "class" => 'obj'));
		}	
		
		return $this -> searchClass($distance);
	}
	
	
	
	private function searchClass($distance)
	{
		$result = array();
		foreach($distance as $data)
			if($data['dist'] <= $this -> k)
				array_push($result, $data);	

		$subj = 0;
		$obj = 0;

		foreach($result as $data)
		{
			if($data['class'] == 'subj')
				$subj++;
			else
				$obj++;
		}
		
		if($subj >= $obj)
			return 'subj';
		else	
			return 'obj';		
	}
	
	
	private function compare($x, $y)
	{
		if ( $x['dist'] == $y['dist'] )
			return 0;
		else if ( $x['dist'] < $y['dist'] )
			return -1;
		else
			return 1;
	}
	
	private function initializeDataSet()
	{
		$this -> dataSetSubj = json_decode(file_get_contents("./src/dataSetSubj.txt"), true);
		$this -> dataSetObj = json_decode(file_get_contents("./src/dataSetObj.txt"), true);
	}
}


?>